<script setup>
import { onMounted, ref } from 'vue';
import { List, Cell, Button,showSuccessToast, showFailToast } from 'vant';
import {getProcessDefinitionPage,onlineProcessDefinition,offlineProcessDefinition} from '@/api/dolphin.js';
import { useRoute } from 'vue-router';

const items = ref([]);
const loading = ref(false);
const finished = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const searchVal = ref('');

const router = useRoute();
// 从路由参数中获取 clusterId 和 projectCode
const clusterId = ref(router.params.clusterId || 'default-cluster-id');
const projectCode = ref(Number(router.params.projectCode) || 12345); // 确保转换为数字类型
// 初始化搜索结果
onMounted(() => {
  onSearch();
});

const onSearch = async () => {
  try {
    // 重置分页和加载状态
    console.log('开始搜索');
    currentPage.value = 1;
    items.value = [];
    loading.value = true;
    finished.value = false;

    const response = await getProcessDefinitionPage(clusterId.value, projectCode.value, currentPage.value, pageSize.value, searchVal.value);
    
    items.value.push(...(response.records || []));
    
    // 如果返回的结果少于请求的数量，则认为已经没有更多数据了
    if (response.totalPages <= response.currentPage) {
      finished.value = true;
    }

    loading.value = false;
    console.log('搜索完成', { items: items.value, finished: finished.value });
    console.log('currentPage.value:',{ currentPage:currentPage.value });
  } catch (error) {
    console.error('搜索工作流定义失败:', error);
    loading.value = false;
  }
};

const onCancel = () => {
  searchVal.value = '';
  // 清除搜索结果并重置状态
  items.value = [];
  loading.value = false;
  finished.value = false;
};



const onLoad = async () => {
  if (finished.value) return; // 如果已经完成加载，则不执行加载更多

  loading.value = true;

  try {
    console.log('开始加载更多');
    currentPage.value++;
    const response = await getProcessDefinitionPage(clusterId.value, projectCode.value, currentPage.value, pageSize.value, searchVal.value);
    items.value.push(...(response.records || []));
    console.log('加载更多完成', { items: items.value, finished: finished.value });
    console.log('currentPage.value:',{ currentPage:currentPage.value });
    // 当加载的数据达到总数量时，设置 finished 为 true
    if (response.totalPages <= response.currentPage) {
      finished.value = true;
    }
  } catch (error) {
    console.error('加载更多项目失败:', error);
  } finally {
    loading.value = false;
    console.log('加载更多完成', { items: items.value, finished: finished.value });
  }
};

// 截断文本并添加省略号
function truncateText(text, maxLength = 12) {
  return text.length > maxLength ? `${text.slice(0, maxLength)}...` : text;
}
// 下线
async function offline(item) {
  try {
    // 等待下线操作完成
    await offlineProcessDefinition(clusterId.value, projectCode.value, item.code);

    // 下线成功后重新搜索以刷新列表
    onSearch();
    
    // 可选: 显示成功的消息给用户
    showSuccessToast('下线成功');
  } catch (error) {
    // 处理错误情况
    console.error('下线失败:', error);
    // 可选: 显示错误信息给用户
    showFailToast('下线失败，请重试');
  }
}

// 上线
async function online(item) {
  try {
    // 等待下线操作完成
    await onlineProcessDefinition(clusterId.value, projectCode.value, item.code);

    // 下线成功后重新搜索以刷新列表
    onSearch();
    
    // 可选: 显示成功的消息给用户
    showSuccessToast('上线成功');
  } catch (error) {
    // 处理错误情况
    console.error('上线失败:', error);
    // 可选: 显示错误信息给用户
    showFailToast('上线失败，请重试');
  }
}



// 弹出层相关的状态管理
const showStartDialog = ref(false);
const currentItem = ref(null);
const startForm = ref({
  failureStrategy: 'CONTINUE',
  warningType: 'NONE',
  taskDependType: 'TASK_POST',
  runMode: 'RUN_MODE_SERIAL',
  processInstancePriority: 'MEDIUM',
  workerGroup: 'default',
  environmentCode: '',
  startParams: '',
  expectedParallelismNumber: '',
  dryRun: 0
});

// 点击开始按钮
const onStart = (item) => {
  currentItem.value = item;
  showStartDialog.value = true;
};

// 确认启动工作流实例
const onConfirmStart = async () => {
  try {
    const params = {
      processDefinitionCode: currentItem.value.code,
      ...startForm.value
    };
    
    await startProcessInstance(clusterId.value, projectCode.value, params);
    showSuccessToast('启动成功');
    showStartDialog.value = false;
    
    // 刷新列表
    onSearch();
  } catch (error) {
    console.error('启动工作流实例失败:', error);
    showFailToast('启动失败');
  }
};

</script>

<template>
    <van-search
      v-model="searchVal"
      placeholder="工作流名称"
      show-action
      @search="onSearch"
      @cancel="onCancel"/>
    <van-list v-model:loading="loading" :finished="finished" @load="onLoad" :offset="100" finished-text="没有更多了">
      <van-cell 
      v-for="(item) in items"
      :key="item.id"
      :title="truncateText(item.name)"
      :label="item.releaseState"
      style="height: 60px;">
        <template #right-icon>
          <van-button 
            round 
            class="button-with-space" 
            type="success" 
            size="small" 
            icon="play-circle-o" 
            v-if="item.releaseState==='ONLINE'" 
            @click="onStart(item)">
          </van-button>
          <van-button round class="button-with-space" color="#EBEAEA" size="small" icon="play-circle-o" v-else></van-button>
          <van-button round class="button-with-space" type="danger" size="small" icon="down"  v-if="item.releaseState==='ONLINE'" @click="offline(item)"></van-button>
          <van-button round class="button-with-space" type="warning" size="small" icon="back-top"  v-else @click="online(item)"></van-button>
          <van-button round class="button-with-space" type="primary" size="small" icon="clock-o"></van-button>
          <van-button round class="button-with-space" type="primary" size="small" icon="calendar-o"></van-button>
        </template>
      </van-cell>
    </van-list>

    <!-- 添加启动工作流实例的弹出层 -->
  <van-popup v-model:show="showStartDialog" position="bottom" :style="{ height: '60%' }">
    <div class="popup-content">
      <van-form @submit="onConfirmStart">
        <van-cell-group inset>
          <van-field
            v-model="startForm.failureStrategy"
            name="failureStrategy"
            label="失败策略"
            placeholder="CONTINUE/END"
            :rules="[{ required: true }]"
          />
          <van-field
            v-model="startForm.warningType"
            name="warningType"
            label="告警类型"
            placeholder="NONE/SUCCESS/FAILURE/ALL"
            :rules="[{ required: true }]"
          />
          <van-field
            v-model="startForm.taskDependType"
            name="taskDependType"
            label="任务依赖类型"
            placeholder="TASK_POST/TASK_PRE"
            :rules="[{ required: true }]"
          />
          <van-field
            v-model="startForm.runMode"
            name="runMode"
            label="运行模式"
            placeholder="RUN_MODE_SERIAL/RUN_MODE_PARALLEL"
            :rules="[{ required: true }]"
          />
          <van-field
            v-model="startForm.processInstancePriority"
            name="processInstancePriority"
            label="实例优先级"
            placeholder="HIGHEST/HIGH/MEDIUM/LOW/LOWEST"
            :rules="[{ required: true }]"
          />
        </van-cell-group>
        <div style="margin: 16px;">
          <van-button round block type="primary" native-type="submit">确认启动</van-button>
        </div>
      </van-form>
    </div>
  </van-popup>
</template>

<style scoped>
.button-with-space {
  margin-right: 1px; /* 设置右侧间距 */
}

.popup-content {
  padding: 16px;
}

</style>
